from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QHeaderView, QAbstractItemView, QTableWidgetItem, QMessageBox

from opsql import rootOp


class Sinfo():
    def __init__(self):
        self.ui = QUiLoader().load('view/学生信息管理.ui')
        self.inittable()
        self.ui.searchBtn.clicked.connect(self.inittable)
        self.ui.addBtn.clicked.connect(self.add)
        self.ui.modifyBtn.clicked.connect(self.modify)
        self.ui.deleteBtn.clicked.connect(self.delete)

    def inittable(self):
        id=self.ui.idIn.text()
        name=self.ui.nameIn.text()
        phone=self.ui.phoneIn.text()
        result = rootOp.searchallstudent(id,name,phone)
        row = 0
        if result:
            row = len(result)
        self.ui.tableWidget.setRowCount(row)
        self.ui.tableWidget.setColumnCount(4)
        self.ui.tableWidget.setHorizontalHeaderLabels(['学生学号','余额','手机号','姓名'])
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.tableWidget.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.ui.tableWidget.verticalHeader().setVisible(False)
        self.ui.tableWidget.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)

        for i in range(row):
            for j in range(4):
                data = QTableWidgetItem(str(result[i][j]))
                self.ui.tableWidget.setItem(i, j, data)

    def add(self):
        id = self.ui.idShow.text()
        money = self.ui.moneyShow.text()
        password = self.ui.passwordShow.text()
        phone = self.ui.phoneShow.text()
        name = self.ui.nameShow.text()
        result = rootOp.addstudent(id, money, password, phone, name)
        if result:
            self.inittable()
            self.ui.idShow.clear()
            self.ui.moneyShow.clear()
            self.ui.passwordShow.clear()
            self.ui.phoneShow.clear()
            self.ui.nameShow.clear()
            QMessageBox.information(self.ui, '提示', '添加成功')
        else:
            QMessageBox.information(self.ui, '提示', '添加失败')

    def modify(self):
        row=self.ui.tableWidget.currentRow()
        sid=self.ui.tableWidget.item(row,0).text()
        money = self.ui.moneyShow.text()
        password = self.ui.passwordShow.text()
        phone = self.ui.phoneShow.text()
        name = self.ui.nameShow.text()
        result = rootOp.modifystudent(money, password, phone, name,sid)
        if result:
            self.inittable()
            QMessageBox.information(self.ui, '提示', '修改成功')
        else:
            QMessageBox.information(self.ui, '提示', '修改失败')

    def delete(self):
        row=self.ui.tableWidget.currentRow()
        sid=self.ui.tableWidget.item(row,0).text()
        result = rootOp.deletestudent(sid)
        if result:
            self.inittable()
            QMessageBox.information(self.ui, '提示', '删除成功')
        else:
            QMessageBox.information(self.ui, '提示', '删除失败')